// pages/foster-detail/foster-detail.js
const app = getApp();
const util = require('../../utils/util.js');

Page({
  data: {
    foster: {},
    isMyPost: false
  },

  onLoad(options) {
    if (options.id) {
      this.loadFosterDetail(options.id);
    }
  },

  onShow() {
    if (this.data.foster.id) {
      this.loadFosterDetail(this.data.foster.id);
    }
  },

  loadFosterDetail(id) {
    app.showLoading();
    const userInfo = wx.getStorageSync('userInfo');
    
    app.request({
      url: `/foster/user/detail/${id}`,
      method: 'GET'
    }).then(res => {
      if (res.success && res.data) {
        const images = res.data.photos ? res.data.photos.split(',') : [];
        const isMyPost = userInfo && userInfo.id === res.data.userId;
        
        this.setData({
          foster: {
            ...res.data,
            images: images,
            createTime: util.formatDateTime(res.data.createTime)
          },
          isMyPost: isMyPost
        });
      }
    }).catch(err => {
      app.showToast('加载失败');
      console.error(err);
    }).finally(() => {
      app.hideLoading();
    });
  },

  editPost() {
    wx.navigateTo({
      url: `/pages/foster-publish/foster-publish?id=${this.data.foster.id}&mode=edit`
    });
  },

  endPost() {
    wx.showModal({
      title: '提示',
      content: '确定要标记为已结束吗？',
      success: (res) => {
        if (res.confirm) {
          this.updateStatus('已结束');
        }
      }
    });
  },

  reopenPost() {
    wx.showModal({
      title: '提示',
      content: '确定要重新开始寻找吗？',
      success: (res) => {
        if (res.confirm) {
          this.updateStatus('寻找中');
        }
      }
    });
  },

  updateStatus(status) {
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo) {
      app.showToast('请先登录');
      return;
    }

    app.showLoading('更新中...');
    app.request({
      url: `/foster/user/updateStatus/${this.data.foster.id}`,
      method: 'POST',
      data: {
        status: status,
        currentUserId: userInfo.id
      }
    }).then(res => {
      if (res.success) {
        app.showToast('更新成功', 'success');
        this.loadFosterDetail(this.data.foster.id);
      } else {
        app.showToast(res.message || '更新失败');
      }
    }).catch(err => {
      app.showToast('更新失败，请稍后重试');
      console.error('更新状态失败', err);
    }).finally(() => {
      app.hideLoading();
    });
  }
});


